var util = require('../../../utils/util.js');
var app = getApp();
var today = util.format(new Date(), 'yyyy-MM-dd');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderRoomArray: [],//房屋数组
    arrays: [{ name: '男', checked: true, value: '1' }, { name: '女', checked: false, value: '0' }],
    live_time: today,//入住时间
    relationArray: [{ key: '同事', value: 1 }, { key: '朋友', value: 2 }, { key: '夫妻', value: 3 }, { key: '父母', value: 4 }, { key: '兄弟', value: 5 }, { key: '姐妹', value: 6 }, { key: '亲戚', value: 7 }, { key: '路人', value: 8 }],
    relationCheck: { value: '', name: '请选择' },
    orderRoomCheck: { value: '', name: '请选择' },
    user_birth: '',//出生日期
    imageList: [],
    imgZ: '',//身份证正面
    imgF: '',//身份证反面
    user_name: '',//用户姓名
    phone_num: '',//电话号码
    relationship_user: '',//与租户的关系
    certificates_no: '',//证件号码
    order_id: '',//订单号
    jurisdiction_end_time: '',
    areaCheck: { value: '', name: '请选择' },//小区
    apartmentCheck: { value: '', name: '请选择' },//公寓
    areaArray: [],
    apartmentArray: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/queryOrderArea", {
          source: res.data.source,
          uid: res.data.user_id,
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            let areaArray = datas.data;
            if (datas.data) {
              that.setData({
                areaArray: areaArray,

              })
            }
          } else {
            var errMsg = '服务器异常';
            if (datas.desc) {
              errMsg = datas.desc;
            }
            wx.showToast({
              title: errMsg,
            })
          }

        })
      }
    });
  },

  /**
   * 选择日期
   */
  bindDateStartChange: function (e) {
    this.setData({
      live_time: e.detail.value,
    })
  },
  /**
   * 选择租户关系
   */
  bindRelationShipChange: function (e) {

    let name = this.data.relationArray[e.detail.value].key;
    let value = e.detail.value;
    let values = this.data.relationArray[e.detail.value].value;
    let relationCheck = { value: value, name: name };

    this.setData({
      relationCheck: relationCheck,
      relationship_user: values,
    })
  },
  /**
   * 选择房源
   */
  bindRoomChange: function (e) {
    let name = this.data.orderRoomArray[e.detail.value].house_address;
    let value = e.detail.value;
    let values = this.data.orderRoomArray[e.detail.value].order_id
    let orderRoomCheck = { value: value, name: name };
    this.setData({
      orderRoomCheck: orderRoomCheck,
      order_id: values.split(',')[0],
      jurisdiction_end_time: util.datetimeFormat(values.split(',')[1])
    })
  },
  /**
   * 出生日期
   */
  bindDateBirthChange: function (e) {
    this.setData({
      user_birth: e.detail.value,
    })
  },
  /**
   * 文件上传
   */

  chooseImage: function (e) {
    var that = this;
    let hidden = e.currentTarget.dataset.value;

    wx.chooseImage({
      count: 1,
      success: function (res) {
        //缓存下
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 2000,
          success: function (ress) {

          }
        })
        var tempFilesSize = res.tempFiles[0].size;  //获取图片的大小，单位B
        if (tempFilesSize <= 2000000) {   //图片小于或者等于2M时 可以执行获取图片
          var tempFilePaths = res.tempFilePaths[0]; //获取图片

          wx.uploadFile({
            url: 'https://landlord.kuailezufang.com/app/home/upload',
            filePath: tempFilePaths,
            method: 'post',
            name: 'file',
            formData: {
              'params': 'idcard'
            },
            success: function (res) {
              let data = JSON.parse(res.data);
              if (data.code == 0) {
                wx.showToast({
                  title: '上传成功',  //标题
                  icon: 'none'       //图标 none不使用图标，详情看官方文档
                })
                that.data.imageList.push(tempFilePaths);   //添加到数组
                that.setData({
                  imageList: that.data.imageList
                })
                if (hidden == 'img1') {
                  that.setData({
                    img1: 'none',
                    imgZ: data.data,
                  })
                } else {
                  that.setData({
                    img2: 'none',
                    imgF: data.data
                  })
                }
              } else {
                wx.showToast({
                  title: data.desc,  //标题
                  icon: 'none'       //图标 none不使用图标，详情看官方文档
                })
              }

              //do something  
            }, fail: function (err) {
              wx.showToast({
                title: '上传失败',  //标题
                icon: 'none'       //图标 none不使用图标，详情看官方文档
              })
            }
          });

        } else {    //图片大于2M，弹出一个提示框
          wx.showToast({
            title: '上传图片不能大于2M!',  //标题
            icon: 'none'       //图标 none不使用图标，详情看官方文档
          })
        }

      }
    })
  },
  /**
   * 浏览图片
   */
  previewImage: function (e) {
    wx.previewImage({
      urls: this.data.imageList
    })
  },

  /**
   * 为空校验
   */
  isNull: function (that) {
    if (that.data.order_id == "") {
      wx.showToast({
        title: "请选择房源",
        icon: 'none'
      })
      return false;
    }
    if (that.data.live_time == "") {
      wx.showToast({
        title: "请选择入住时间",
        icon: 'none'
      })
      return false;
    }
    if (that.data.user_name == "") {
      wx.showToast({
        title: "请输入住户姓名",
        icon: 'none'
      })
      return false;
    }
    if (that.data.phone_num == "") {
      wx.showToast({
        title: "请输入手机号码",
        icon: 'none'
      })

      return false;
    }
    if (that.data.relationship_user == '') {
      wx.showToast({
        title: "请选择与租户关系",
        icon: 'none'
      })
      return false;
    }
    return true;
  },
  /**
   * 性别选择
   */
  listenerRadioGroup: function (e) {
    let value = e.detail.value;
    let arr = this.data.arrays
    for (let i = 0; i < arr.length; i++) {
      arr[i].checked = false;
      if (arr[i].value == value) {
        arr[i].checked = true;
      }
    }
    this.setData({
      arrays: arr,
    })
  },
  /**
   * 用户填写
   */
  userInput: function (e) {
    this.setData({
      user_name: e.detail.value,
    })
  },
  /**
   * 电话号码填写
   */
  phoneInput: function (e) {
    this.setData({
      phone_num: e.detail.value,
    })
  },
  /**
   * 身份证号码填写
   */
  idcardInput: function (e) {
    this.setData({
      certificates_no: e.detail.value,
    })
  },
  /**
   * 保存提示
   */
  nagtiveToZd: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定保存吗?',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '保存中请稍后...',
            mask: true,
          })
          that.savesubmit(that);

        }
      }
    })
  },

  /**
   * 保存文件
   */
  savesubmit: function (that) {
    if (!that.isNull(that)) {
      return;
    }

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data
        })
        let arrays = that.data.arrays;
        let user_sex = '';
        for (let i = 0; i < arrays.length; i++) {
          if (arrays[i].checked == true) {
            user_sex = arrays[i].value;
            break;
          }
        }
        util.getReq("/app/home/userInfoAdd", {
          source: res.data.source,
          uid: res.data.user_id,
          phone_num: res.data.phone_num,
          user_name: res.data.user_name,
          "checkIn.order_id": that.data.order_id,
          "checkIn.live_time": that.data.live_time,
          "checkIn.jurisdiction_begin_time": that.data.live_time,
          "checkIn.relationship_user": that.data.relationship_user,
          'checkIn.jurisdiction_end_time': that.data.jurisdiction_end_time,
          "user.user_name": that.data.user_name,
          "user.user_sex": user_sex,
          "user.phone_num": that.data.phone_num,
          "user.certificates_img": that.data.imgZ,
          "user.opposite_img": that.data.imgF,
          "user.user_birth": that.data.user_birth,
          'user.certificates_no': that.data.certificates_no,
        }, function (datas) {
          if (datas.code == 0) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 1000,
            })
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/home/home',
              })

            }, 1000);

          } else {
            wx.hideLoading();
            var errMsg = '服务器异常';
            if (datas.desc) {
              errMsg = datas.desc;
            }
            wx.showToast({
              title: errMsg,  //标题
              icon: 'none',      //图标 none不使用图标，详情看官方文档
              duration: 3000,
            })
          }

        })
      }
    });
  },
  /**
   * 小区选择
   */
  bindAreaChange: function (e) {
    var that = this;
    let name = that.data.areaArray[e.detail.value].village_name;
    let value = e.detail.value;
    let values = that.data.areaArray[e.detail.value].village_id
    let areaCheck = { value: value, name: name };
    let orderRoomCheck = { value: '', name: '请选择' };
    let apartmentCheck = { value: '', name: '请选择' };
    that.setData({
      areaCheck: areaCheck,
      apartmentCheck: apartmentCheck,
      orderRoomCheck: orderRoomCheck,
      apartmentArray: [],
      orderRoomArray: [],
    })

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        util.getReq("/app/home/queryOrderApartment", {
          source: res.data.source,
          uid: res.data.user_id,
          village_id: values
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            if (datas.data) {
              let apartmentArray = datas.data;
              that.setData({
                apartmentArray: apartmentArray,

              })

            } else {
              var errMsg = '服务器异常';
              if (datas.desc) {
                errMsg = datas.desc;
              }
              wx.showToast({
                title: errMsg,
              })
            }
          }
        })
      }
    });
  },
  /**
  * 公寓选择
  */
  bindApartmentChange: function (e) {
    var that = this;
    let name = that.data.apartmentArray[e.detail.value].apartment_name;
    let value = e.detail.value;
    let values = that.data.apartmentArray[e.detail.value].apartment_id;
    let apartmentCheck = { value: value, name: name };
    let orderRoomCheck = { value: '', name: '请选择' };
    that.setData({
      apartmentCheck: apartmentCheck,
      orderRoomCheck: orderRoomCheck,
      orderRoomArray: [],
    })

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,

        })
        util.getReq("/app/home/queryOrderRoom", {
          source: res.data.source,
          uid: res.data.user_id,
          phone_num: res.data.phone_num,
          user_name: res.data.user_name,
          apartment_id: values
        }, function (datas) {
          wx.hideLoading();
          if (datas.code == 0) {
            let orderRoomArray = [];
            for (let i = 0; i < datas.data.length; i++) {
              orderRoomArray.push({
                'order_id': datas.data[i].order_id + "," + datas.data[i].plan_end_time,
                'house_address': datas.data[i].room_code+'室'
              })
            }

            if (datas.data) {
              that.setData({
                orderRoomArray: orderRoomArray,

              })

            } else {
              var errMsg = '服务器异常';
              if (datas.desc) {
                errMsg = datas.desc;
              }
              wx.showToast({
                title: errMsg,
              })
            }
          }
        })
      }
    });
  }
})
